var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    submitData: {
      legalPerson: ''
    },
    authenticationFalse: false,
    buthidden: false,
    previewImgIdCard: true,
    previewImgDriving: true,
    ifUploadIdCardText: '请上传',
    ifUploadDringText: '请上传',
    FileIDrivingPaths: '',
    FileIdCardPaths: '',
    tempFilePaths: '',
    sourceType: ['album', 'camera'],
    ifshowIdCardInfo: false,
    ifshowDrivingInfo: false,
    cardVo: {},
    drivingVo: {},
    userVo: '',
    checks: [
      {
        name: '废纸类',
        value: '0',
        checked: false
      },
      {
        name: '废塑料类',
        value: '1',
        checked: false
      },
      {
        name: '废金属',
        value: '2',
        checked: false
      },
      {
        name: '废钢铁',
        value: '3',
        checked: false
      },
      {
        name: '废纺织品',
        value: '4',
        checked: false
      },
      {
        name: '二手设备',
        value: '4',
        checked: false
      }
    ],
    checksAbled: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    that.onMineInfo();
    try {
      var res = wx.getSystemInfoSync();
      var platform = res.platform;
      if (platform == 'ios') {
        util.msg('警告', 'IOS系统暂不支持拍照，请从相册选择照片');
        this.setData({
          sourceType: ['album']
        });
      }
    } catch (e) {}
  },

  onMineInfo: function() {
    wx.showLoading({ title: '加载中' });
    var that = this;
    wx.request({
      method: 'POST',
      url: app.preUrl + 'findByUserId',
      dataType: 'json',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        userId: app.globalData.userId
      },
      success: function(res) {
        wx.hideLoading();
        that.setData({ userVo: res.data.result });
        if (res.data.result.auditStatus == 3) {
          //已经认证 ===3
          console.log(res);
          that.getMineInfo();
          that.setData({
            ifUploadIdCardText: '已上传',
            ifshowIdCardInfo: true, //已上传
            previewImgIdCard: true,
            buthidden: true,
            ifUploadDringText: '已上传',
            ifshowDrivingInfo: true,
            previewImgDriving: true,
            authenticationFalse: true
          });
        } else {
          that.setData({
            ifUploadIdCardText: '请上传',
            ifUploadDringText: '请上传',
            authenticationFalse: false //未上传
          });
        }
      },
      fail: function(error) {
        console.log(error);
      }
    });
  },
  getMineInfo: function() {
    wx.showLoading({ title: '加载中' });
    var that = this;
    wx.request({
      method: 'POST',
      url: app.preUrl + 'getCertificatesUserId',
      dataType: 'json',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        userId: app.globalData.userId
      },
      success: function(res) {
        wx.hideLoading();
        if (res.data.code == 100) {
          console.log(res);
          let data = res.data.result;
          let cardVo = {
            cardNum: data.cardNum,
            cardAddress: data.cardAddress,
            cardSex: data.cardSex,
            cardName: data.cardName,
            cardBirth: data.cardBirth,
            cardUrl: data.cardUrl
          };
          let drivingVo = {
            legalPerson: data.legalPerson,
            name: data.name,
            unifiedCode: data.unifiedCode,
            residence: data.residence,
            img: data.img,
            registeredCapital: data.registeredCapital
          };
          let checksAbled = data.range.split(',');
          let checks = that.data.checks;
          checksAbled.forEach(function(item1, index1) {
            checks.forEach(function(item2, index2) {
              if (item1 == item2.name) {
                item2.checked = true;
              }
            });
          });
          that.setData({ checks: checks });
          that.setData({
            cardVo,
            drivingVo,
            FileIdCardPaths: data.cardUrl,
            FileIDrivingPaths: data.img
          });
        }
      },
      fail: function(error) {
        console.log(error);
      }
    });
  },

  //上传身份证
  chooseImageIdCard: function() {
    // console.log(111)
    var that = this;
    var Type = that.data.sourceType;
    if (that.data.userVo.auditStatus != 3) {
      wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: Type, // 可以指定来源是相册还是相机，默认二者都有
        success: function(res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          that.setData({
            FileIdCardPaths: res.tempFilePaths
          });
          wx.showLoading({
            title: '上传中'
          });
          wx.uploadFile({
            url: app.preUrl + 'uploadCardFile',
            filePath: that.data.FileIdCardPaths[0], //图片路径，如tempFileIdCardPaths[0]
            name: 'file',
            // userId: app.globalData.userId,
            header: {
              'Content-Type': 'multipart/form-data'
            },
            formData: {
              userId: app.globalData.userId //附加信息为用户ID
            },
            success: function(res) {
              wx.hideLoading();
              console.log(res);
              var cardVoStr = JSON.parse(res.data);
              if (cardVoStr.code == 100) {
                that.setData({
                  previewImgIdCard: false,
                  ifUploadIdCardText: '已上传',
                  cardVo: cardVoStr.result
                });
                wx.showToast({
                  title: '上传成功',
                  icon: 'success',
                  duration: 1000
                });
              } else {
                wx.showModal({
                  title: '提示',
                  content: cardVoStr.message,
                  confirmColor: '#56BDE0',
                  showCancel: false
                });
              }
            },
            fail: function(err) {
              console.log(err);
            }
          });
        }
      });
    }
  },
  //上传营业执照
  chooseImageDriving: function() {
    // console.log(222)
    var that = this;
    var Type = that.data.sourceType;
    if (that.data.userVo.auditStatus != 3) {
      wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: Type, // 可以指定来源是相册还是相机，默认二者都有
        success: function(res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          that.setData({
            FileIDrivingPaths: res.tempFilePaths
          });
          wx.showLoading({
            title: '上传中'
          });
          wx.uploadFile({
            url: app.preUrl + 'uploadIndustryFile',
            filePath: that.data.FileIDrivingPaths[0], //图片路径，如tempFileIdCardPaths[0]
            name: 'file',
            // userId: app.globalData.userId,
            header: {
              'Content-Type': 'multipart/form-data'
            },
            formData: {
              userId: app.globalData.userId //附加信息为用户ID
            },
            success: function(res) {
              wx.hideLoading();
              var cardVoStr = JSON.parse(res.data);
              // console.log('cardVoStr', JSON.parse(res.data))
              if (cardVoStr.code == 100) {
                that.setData({
                  previewImgDriving: false,
                  ifshowDrivingInfo: true,
                  ifUploadDringText: '已上传',
                  drivingVo: cardVoStr.result
                });
                wx.showToast({
                  title: '上传成功',
                  icon: 'success',
                  duration: 1000
                });
              } else {
                wx.showModal({
                  title: '提示',
                  content: cardVoStr.message,
                  confirmColor: '#56BDE0',
                  showCancel: false
                });
              }
            },
            fail: function(err) {
              console.log(err);
            }
          });
        }
      });
    }
  },
  getTextByJs(arr) {
    //拼接字符串
    var str = '';
    for (var i = 0; i < arr.length; i++) {
      str += arr[i] + ',';
    }
    //去掉最后一个逗号(如果不需要去掉，就不用写)
    if (str.length > 0) {
      str = str.substr(0, str.length - 1);
    }
    return str;
  },
  updateUserStatus: function() {
    var that = this;
    // var identityStatus = that.data.identityStatus
    let drivingVo = this.data.drivingVo;
    let cardVo = this.data.cardVo;
    let checksAbled = that.data.checksAbled;
    if (cardVo.cardNum == undefined) {
      wx.showModal({
        title: '请上传身份证照片',
        confirmColor: '#56BDE0',
        showCancel: false
      });
      return false;
    } else if (drivingVo.legalPerson == undefined) {
      wx.showModal({
        title: '请上传营业执照',
        confirmColor: '#56BDE0',
        showCancel: false
      });
      return false;
    } else if (checksAbled.length <= 0) {
      wx.showToast({ title: '经营范围必选', icon: 'none' });
      return false;
    } else {
      that.setData({ buthidden: true });
      let rangeStr = that.getTextByJs(checksAbled);
      wx.showLoading({ title: '提交中' });
      wx.request({
        method: 'POST',
        url: app.preUrl + 'saveSiteIndustry',
        dataType: 'json',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          userId: app.globalData.userId, //cardVo ,drivingVo
          legalPerson: drivingVo.legalPerson,
          name: drivingVo.name,
          unifiedCode: drivingVo.unifiedCode,
          residence: drivingVo.residence,
          img: drivingVo.img,
          registeredCapital: drivingVo.registeredCapital,
          range: rangeStr, //经营范围
          cardNum: cardVo.cardNum,
          cardAddress: cardVo.cardAddress,
          cardSex: cardVo.cardSex,
          cardName: cardVo.cardName,
          cardBirth: cardVo.cardBirth,
          cardUrl: cardVo.cardUrl
        },
        success: function(res) {
          console.log(res);
          wx.hideLoading();
          if (res.data.code == 100) {
            that.setData({ ifshowIdCardInfo: true });
            wx.showToast({
              title: '身份认证成功',
              icon: 'success',
              duration: 1000
            });

            setTimeout(function() {
              wx.reLaunch({
                url: 'mine'
              });
            }, 1000);
          } else {
            wx.showModal({
              title: '请与管理员联系',
              confirmColor: '#56BDE0',
              showCancel: false
            });
            that.setData({ buthidden: false });
          }
        },
        fail: function(error) {}
      });
    }
  },

  clicks: function(e) {
    if (this.data.userVo.auditStatus == 3) {
      return;
    }
    let index = e.currentTarget.dataset.index;
    let arrs = this.data.checks;
    let checksAbled = [];
    let array = new Array();
    let text = e.currentTarget.dataset.text;
    if (arrs[index].checked == false) {
      arrs[index].checked = true;
      array.push(text);
    } else {
      arrs[index].checked = false;
    }
    this.setData({
      checks: arrs
    });
    this.data.checks.forEach(function(item, index) {
      if (item.checked == true) {
        checksAbled.push(item.name);
      }
    });
    this.setData({ checksAbled });
  }
});
